package com.supermap.wzhy.module.data.api;

import com.supermap.wzhy.common.annotation.Permission;
import com.supermap.wzhy.common.annotation.Role;
import com.supermap.wzhy.util.tree.DHTMLXTree;
import com.supermap.wzhy.util.tree.DHTMLXTreeFactory;
import com.supermap.wzhy.common.api.BaseController;
import com.supermap.wzhy.data.OpStatus;
import com.supermap.wzhy.data.cons.CMicroMetaType;
import com.supermap.wzhy.entity.TMicroIdenmeta;
import com.supermap.wzhy.entity.TMicroTablemeta;
import com.supermap.wzhy.entity.TUsers;
import com.supermap.wzhy.module.data.service.MicroIdenmetaService;
import com.supermap.wzhy.module.data.service.MicroTablemetaService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by W.Qiong on 14-3-4.
 * Updated by R.ruping on 15-8-14
 * 基层元数据
 */
@Controller
@RequestMapping(value = {"/micro","/service/micro"})
public class MicroTablemetaController extends BaseController {
    @Autowired
    MicroTablemetaService microTablemetaService;
    @Autowired
    MicroIdenmetaService microIdenmetaService;

    /**
     * 查询用户所有可用的【基层数据对象】
     * @param metaType 基层数据类型（1调查对象、2统计范围、3定报表模板、4目录树、5系统显示配置）
     * @param catalogId 关联地图（行政区划）ID
     * @param moduleId 业务模块ID（空：表示不限制基层数据）
     * @return
     */
    @Transactional
    @Permission(Role.USER)
    @RequestMapping(value = "/items", method = RequestMethod.GET)
    @ResponseBody
    public List<TMicroTablemeta> getAllItems(HttpServletRequest request, int metaType, int catalogId, String moduleId, Integer major, Integer reportType) {
        TUsers currUser = getSessionUser(request);
        List<TMicroTablemeta> re = new ArrayList<>();
        List<TMicroTablemeta> tablemetas = new ArrayList<>();

        if(major!=null && reportType!=null){
            tablemetas = microTablemetaService.findMicrosByMajorAndReportType(metaType,catalogId, reportType, major);
        }else{
            if(catalogId == -1){
                tablemetas = microTablemetaService.findMicros(metaType);//不关联行政区划树
            }else{
                if(moduleId==null || moduleId.equals("")){
                    tablemetas = microTablemetaService.findMicroTablemetas(metaType, catalogId);//不限制模块
                }else {
                    tablemetas = microTablemetaService.findMicroTablemetas(metaType, catalogId, moduleId);
                }
            }
        }
        return tablemetas ;
    }

    /**
     * 根据Id查找基层数据元数据
     *
     * @param microid
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}", method = RequestMethod.GET)
    @ResponseBody
    public TMicroTablemeta getItem(@PathVariable("microid") int microid) {
        return microTablemetaService.one(microid);
    }

    /**
     * 创建调查对象（包括权限）
     *
     * @param tablemeta
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus addMicrObject(HttpServletRequest request , @RequestBody TMicroTablemeta tablemeta) {
        TUsers currUser = getSessionUser(request);
        int rcid = tablemeta.getTRegioncatalog().getRcid() ;
        TMicroTablemeta t = microTablemetaService.create(rcid, tablemeta);//创建调查对象
        //初始指标权限
        List<TMicroIdenmeta> idenmetas = microIdenmetaService.findMicroIdentinfosByItem(t.getMitmid());

        return getOpStatus(true);
    }

    /**
     * 创建基层模板
     * @param template
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/template", method = RequestMethod.POST)
    @ResponseBody
    public TMicroTablemeta addMicrTemplate(TMicroTablemeta template) {
        TMicroTablemeta re = microTablemetaService.create(template);
        return re;
    }

    /**
     * 更新调查对象
     *
     * @param microid
     * @param tablemeta
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}", method = RequestMethod.PUT)
    @ResponseBody
    public OpStatus updateMicrObject(@PathVariable int microid,  @RequestBody TMicroTablemeta tablemeta) {
        boolean re = microTablemetaService.update(microid, tablemeta);
        return getOpStatus(re);
    }

    /**
     * 删除调查对象（包括权限）
     *
     * @param microid
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}", method = RequestMethod.DELETE)
    @ResponseBody
    public OpStatus deleteMicrObject(HttpServletRequest request ,@PathVariable int microid) {
        TUsers currUser = getSessionUser(request);
        List<TMicroIdenmeta> idenmetas = microIdenmetaService.findMicroIdentinfosByItem(microid);
        TMicroTablemeta t = microTablemetaService.delete(microid);
        return getOpStatus(false);
    }

    /**
     * 通过基层数据元数据ID，查找单位指标元数据
     *
     * @param microid
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}/indicators", method = RequestMethod.GET)
    @ResponseBody
    public List<TMicroIdenmeta> getMacroIdentinfosByItem(HttpServletRequest request ,@PathVariable("microid") int microid) {
        TUsers currUser = getSessionUser(request);
        TMicroTablemeta tablemeta = this.microTablemetaService.one(microid);//基层对象
        List<TMicroIdenmeta> idenmetas = this.microIdenmetaService.findMicroIdentinfosByItem(microid);//基层对象指标
        if(idenmetas.size()<0){
            System.out.println("基层对象【"+microid+"】:未配置有效指标");
        }
        List<TMicroIdenmeta> re = new ArrayList<>();
        return re  ;
    }


    /**
     * 通过基层元数据，查找一条元数据指标
     *
     * @param microid
     * @param indicatorid
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}/indicators/{indicatorid}", method = RequestMethod.GET)
    @ResponseBody
    public TMicroIdenmeta getOneMicroIdentinfo(@PathVariable("microid") int microid, @PathVariable("indicatorid") int indicatorid) {
        return microIdenmetaService.findOneIdenmeta(microid, indicatorid);
    }

    /** 添加指标元数据 */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}/indicators", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus addIdenToMicrObject(HttpServletRequest request ,@PathVariable("microid") int microid ,@RequestBody TMicroIdenmeta idenmeta) {
        TUsers currUser = getSessionUser(request);
        TMicroTablemeta tablemeta = microTablemetaService.one(microid);
        if(null==tablemeta){
            return  new OpStatus(false,"调查对象不存在",null);
        }
        List<TMicroIdenmeta> idenmetas = microIdenmetaService.checkNameIsExist(idenmeta.getIdenName()) ;
        if(null!=idenmetas&&idenmetas.size()>0){
            //取最新的
            TMicroTablemeta par = idenmetas.get(idenmetas.size()-1).getTMicroTablemeta() ;
            try {
                //开库操作后导致悬空的指标，不归属于任何对象
                par.getName() ;
                return  new OpStatus(false,"指标"+idenmeta.getIdenName()
                        +"已经存在,"+"请从'"+(par.getMicmetaType()!=1?"模板:":"调查对象:")+par.getName()+"'中复制",null);
            }catch (Exception e){
                return  new OpStatus(false,"指标"+idenmeta.getIdenName()
                        +"已经存在,请从其他调查对象或者模板中进行复制",null);
            }
        }
        TMicroIdenmeta t = microIdenmetaService.create(microid, idenmeta);
        boolean re = null!=t;
        return new OpStatus(re,re?"创建指标成功":"创建指标失败",null);
    }

    /** 添加指标元数据【公用】 */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}/createiden", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus addIdenToMicroObject(HttpServletRequest request ,@PathVariable("microid") int microid ,@RequestBody TMicroIdenmeta idenmeta) {
        TUsers currUser = getSessionUser(request);
        TMicroTablemeta tablemeta = microTablemetaService.one(microid);
        if(null==tablemeta){
            return  new OpStatus(false,"调查对象不存在",null);
        }
        TMicroIdenmeta t = null;
        try {
            t = microIdenmetaService.create(microid, idenmeta);
        }catch (Exception e){
            return new OpStatus(false,"创建指标失败",null);
        }
        boolean re = null!=t;
        return new OpStatus(re,re?"创建指标成功":"创建指标失败",null);
    }

    /**
     * 更新指标元数据
     *
     * @param microid
     * @param indicatorid
     * @param idenmeta
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}/indicators/{indicatorid}", method = RequestMethod.PUT)
    @ResponseBody
    public OpStatus updateMicrObjectIden(@PathVariable("microid") int microid, @PathVariable("indicatorid") int indicatorid  , @RequestBody TMicroIdenmeta idenmeta) {
        boolean re = microIdenmetaService.update(indicatorid, idenmeta);
        return getOpStatus(re);
    }

    /**
     * 删除指标元数据
     *
     * @param microid
     * @param indicatorids
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}/indicators/{indicatorid}", method = RequestMethod.DELETE)
    @ResponseBody
    public OpStatus deleteMicrObjectIden(HttpServletRequest request ,@PathVariable("microid") int microid,@RequestBody int[] indicatorids) {
        TUsers currUser = getSessionUser(request);
        List<TMicroIdenmeta> t= microIdenmetaService.delete(microid, indicatorids);
        boolean re = t.size()>0;
        return getOpStatus(re);
    }

    /**
     * 获取指标复制（模板）树
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/copytree", method = RequestMethod.GET)
    @ResponseBody
    public  String getCopyTree(){
        DHTMLXTree root = new DHTMLXTree("root","指标模板树 ").noCheckbox().open();
        List<TMicroTablemeta> objs = microTablemetaService.findMicros(CMicroMetaType.OBJECT_TYPE);
        List<TMicroTablemeta> templs = microTablemetaService.findMicros(CMicroMetaType.TABLE_TEMPLATE_TYPE);
        templs.addAll(objs);
        for(TMicroTablemeta o:templs){
            DHTMLXTree node = new DHTMLXTree(o.getMitmid()+"_T",o.getName());
            List<TMicroIdenmeta> inds = microIdenmetaService.findMicroIdentinfosByItem(o.getMitmid());
            for(TMicroIdenmeta ind :inds){
                node.add(new DHTMLXTree(ind.getMiimid()+"_F",ind.getIdenName()));
            }
            root.add(node);
        }
        return DHTMLXTreeFactory.toTree(root) ;
    }


    /**
     * 复制指标
     *
     * @param microid
     * @param idens
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}/indicators/copy", method = RequestMethod.POST)
    @ResponseBody
    public OpStatus copyMicrObjectIden(HttpServletRequest request,@PathVariable("microid") int microid, String idens) {
        TUsers currUser = getSessionUser(request);
        List<TMicroIdenmeta> t = microIdenmetaService.copyIdenmeta(microid, idens);
        boolean re = t.size()>0;
        return new OpStatus(re,re?"成功复制指标"+t.size()+"个":"复制失败",null);
    }

    /**
     * 基层数据元数据对应单位指标元数据导入
     *
     * @param microid
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}/indicators/import", method = RequestMethod.GET)
    @ResponseBody
    public OpStatus importMicroIdens(@PathVariable("microid") int microid, String path) {
        return getOpStatus(false);
//       return microIdenmetaService.importIdenmeta(microid,path);
    }

    /**
     * 基层数据元数据对应单位指标元数据导出
     *
     * @param microid
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}/indicators/export", method = RequestMethod.GET)
    @ResponseBody
    public boolean exportIdens(@PathVariable("microid") int microid, String path) {
        return microIdenmetaService.exprotIdenmeta(microid, path);
    }

    /**
     * 下载 基层数据导入模板
     * @param microid
     * @param type 坐标来源类型
     * @return
     */
    @Permission(Role.USER)
    @RequestMapping(value = "/items/{microid}/template/download", method = RequestMethod.GET)
    @ResponseBody
    public boolean downloadTemplate(HttpServletRequest request,@PathVariable("microid")int microid,String type) {
        HSSFWorkbook wk = microTablemetaService.downloadTemplate(microid,type);
        request.getSession().setAttribute("fileName","基层数据导入模板");
        request.getSession().setAttribute("wk",wk);
        return true;
    }

}
